<template>
  <page>
    <template v-slot:header>
      <h2>
        <i class="el-icon-s-platform"></i>
        <span>{{ $t("system.systems") }}</span>
      </h2>
    </template>
    <template v-slot:global-button>
      <el-button class="kylin-button" @click="downloadTemplate">
        {{ $t("system.password_template_download") }}
      </el-button>
    </template>
    <template v-slot:search>
      <search>
        <div>
          <el-select
            v-model="search_criteria.panel"
            size="small" class="size"
          >
            <el-option
              v-for="item in panels"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </div>
        <div v-if="search_criteria.panel == 1 || search_criteria.panel == 2">
          <span class="label">{{ $t("patch.package") }}</span>
          <virtual-list
            :value="search_criteria.pack"
            size="small"
            class="size"
            @selectValue="handlePackageSelect"
            :list="packages"
          ></virtual-list>
        </div>
        <div v-if="search_criteria.panel == 3">
          <span class="label">{{
            $t("configure.configure_item")
          }}</span>
          <virtual-list
            v-model="search_criteria.configure"
            size="small"
            class="size"
            :list="configures"
            @selectValue="handleConfigureSelect"
          ></virtual-list>
        </div>
        <div v-show="search_criteria.panel == 4">
          <span class="label">CVE</span>
          <virtual-list
            v-model="search_criteria.cve"
            size="small"
            :multiple="true"
            :list="cves"
            @selectValue="handleCveSelect"
          ></virtual-list>
        </div>
        <div
          v-if="
            search_criteria.panel == 1 ||
            search_criteria.panel == 3 ||
            search_criteria.panel == 5
          "
        >
          <span class="label">{{ $t("rule_comparison") }}</span>
          <el-select
            v-model="search_criteria.rule"
            size="small"
            class="size"
            clearable
          >
            <el-option
              v-for="item in rules"
              :key="item.name"
              :value="item.value"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </div>
        <div v-if="search_criteria.panel == 1">
          <span class="label">{{
            $t("patch.package_version")
          }}</span>
          <el-select
            v-model="search_criteria.version"
            clearable
            size="small"
            class="size"
          >
            <el-option
              v-for="item in versions"
              :key="item"
              :value="item"
              :label="item"
            >
            </el-option>
          </el-select>
        </div>
        <div v-if="search_criteria.panel == 3">
          <span class="label">{{
            $t("configure.compare_value")
          }}</span>
          <el-input
            size="small"
            class="size"
            style="display: inline-block"
            :showClear="true"
            v-model="search_criteria.compare_value"
            clearable
          ></el-input>
        </div>
        <div v-if="search_criteria.panel == 5">
          <span class="label">{{
            $t("system.agent_version")
          }}</span>
          <el-select
            v-model="search_criteria.agentVersion"
            clearable
            size="small"
            class="size"
          >
            <el-option
              v-for="item in agentVersions"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </div>
        <div>
          <el-button
            size="small"
            class="kylin-add-button kylin-button"
            v-if="search_criteria.panel == 3"
            @click="handleAddConfigure"
            ><i class="el-icon-plus"></i
          ></el-button>
          <el-button
            size="small"
            class="kylin-button"
            @click="handleSearch"
            >{{ $t("Search") }}</el-button
          >
          <el-button
            size="small"
            class="kylin-button"
            @click="handleReset"
            >{{ $t("Reset") }}</el-button
          >
        </div>
      </search>
    </template>
    <template v-slot:content>
      <div
        class="system-configure-search"
        v-if="search_criteria.configureObj.length > 0"
      >
        <el-tag
          v-for="tag in search_criteria.configureObj"
          :key="tag.name"
          closable
          @close="handleTagClose(tag)"
        >
          {{ tag.name + ";" + tag.compare + ";" + tag.value }}
        </el-tag>
      </div>
      <el-dialog
        :title="title"
        :visible.sync="display"
        :before-close="handleClose"
      >
        <mark-batch
          v-if="type === 'mark_batch'"
          @click="handleClose"
          :ids="ids"
        ></mark-batch>
        <system-register
          v-else-if="type === 'register'"
          @click="handleClose"
        ></system-register>
        <delete
          v-else-if="type === 'delete'"
          :content="delete_content"
          @click="handleClose"
          :handleCancel="handleClose"
          :handleOk="handleDeleteOk"
        >
        </delete>
      </el-dialog>
      <ky-table
        ref="table"
        :search_criteria="search_criteria"
        :getData="getHostList"
        :showSelect="showSelect"
        :search_data="search_data"
      >
        <template v-slot:table-action>
          <el-dropdown trigger="click">
            <el-button class="kylin-item-button">
              {{ $t("system.agent_operation")
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <authorization-dropdown-item @click.native="handleRegister"
                ><span>{{
                  $t("system.register")
                }}</span></authorization-dropdown-item
              >
              <authorization-dropdown-item
                @click.native="handleDelete"
                :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
                ><span>{{
                  $t("system.uninstall")
                }}</span></authorization-dropdown-item
              >
              <authorization-dropdown-item
                @click.native="handleDelete('upgrade')"
                :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
                ><span>{{
                  $t("system.upgrade")
                }}</span></authorization-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown trigger="click">
            <el-button
              class="kylin-item-button"
              :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
            >
              {{ $t("action")
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <authorization-dropdown-item
                @click.native="handleMarkBatch"
                name="batches:mark"
                >{{ $t("system.mark_batch") }}</authorization-dropdown-item
              >
              <authorization-dropdown-item
                @click.native="handleScanNow"
                name="scan:now"
                >{{ $t("system.scan_now") }}</authorization-dropdown-item
              >
              <authorization-dropdown-item
                :disabled="$refs.table && $refs.table.selectRow.ids.length != 2"
                @click.native="handleCompare"
                name="HostCompare:compare"
              >
                <span>{{ $t("system.compare") }}</span>
              </authorization-dropdown-item>
              <authorization-dropdown-item @click.native="handleDownloadHost">{{
                $t("system.export_select")
              }}</authorization-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template v-slot:table>
          <el-table-column :label="$t('system.ip_address')">
            <template slot-scope="scope">
              <router-link :to="$route.path + scope.row.id">
                {{ scope.row.ip }}
              </router-link>
            </template>
          </el-table-column>
          <el-table-column :label="$t('system.status')">
            <template slot-scope="scope">
              <span
                v-if="scope.row.agentStatus == '连接'"
                class="el-icon-success success"
              ></span>
              <span v-else class="el-icon-error error"></span>
              {{ scope.row.agentStatus }}
            </template>
          </el-table-column>
          <el-table-column
            prop="operatingSystem"
            width="210"
            :label="$t('system.operating_system')"
          >
          </el-table-column>
          <el-table-column prop="version" :label="$t('system.version')">
          </el-table-column>
          <el-table-column
            prop="architecture"
            :label="$t('system.architecture')"
          >
          </el-table-column>
          <el-table-column
            prop="agentVersion"
            :label="$t('system.agent_version')"
          >
          </el-table-column>
          <el-table-column
            prop="installTime"
            :label="$t('system.install_time')"
          >
          </el-table-column>
        </template>
      </ky-table>
    </template>
  </page>
</template>

<script>
import Page from "@/components/Page";
import Search from "@/components/Search";
import virtualList from "@/components/virtualList";
import kyTable from "@/components/KyTable";
import {
  getAgentVersionHost,
  uninstallAgent,
  upgradeAgent,
  getConfigureHost,
  downloadHosts,
  getAgentVersionList,
} from "@/api/system";
import { getConfigureNames } from "@/api/config";
import { getCveNumberList } from "@/api/errata";
import {
  getPackageNames,
  getPackageVersion,
  getcveHosts,
  getPackageHosts,
  getPackageChangeHosts,
} from "@/api/host_detail";
import { scanNow } from "@/api/scan";
import MarkBatch from "./form/markBatch.vue";
import SystemRegister from "./form/systemRegister.vue";
import Delete from "@/components/Delete";
import { download } from "@/utils";
import { downloadTemplate } from "@/api/template";
import AuthorizationDropdownItem from "@/components/AuthorizationDropdownItem";
export default {
  name: "system",
  components: {
    Page,
    Search,
    virtualList,
    kyTable,
    MarkBatch,
    SystemRegister,
    Delete,
    AuthorizationDropdownItem,
  },
  data() {
    return {
      display: false,
      delete_content: "",
      type: "",
      title: "",
      ids: [],
      expand: false,
      search_criteria: {
        configure: "",
        panel: 5,
        rule: "",
        version: "",
        compare_value: "",
        pack: "",
        cve: [],
        agentVersion: "",
        sortBy: "ip",
        sortOrder: "asc",
        configureObj: [],
      },
      span: 4,
      cves: [],
      agentVersions: [],
      panels: [
        { id: 5, name: this.$t("system.all_host") },
        { id: 1, name: this.$t("system.package_version") },
        { id: 2, name: this.$t("system.package_change_log") },
        { id: 3, name: this.$t("system.configure_diffrent") },
        { id: 4, name: this.$t("system.patch_install_status") },
      ],
      packages: [],
      configures: [],
      rules: [
        {
          name: this.$t(">="),
          value: ">=",
        },
        {
          name: this.$t("<="),
          value: "<=",
        },
        {
          name: this.$t(">"),
          value: ">",
        },
        {
          name: this.$t("<"),
          value: "<",
        },
        {
          name: this.$t("="),
          value: "=",
        },
      ],
      versions: [],
      showSelect: true,
      search_data: {
        ip: {
          name: "system.ip_address",
          type: "text",
        },
        agentStatus: {
          name: "system.status",
          type: "select",
          items: [
            { key: this.$t("break"), name: this.$t("break") },
            { key: this.$t("connect"), name: this.$t("connect") },
          ],
        },
        osInfo: {
          name: "system.operating_system",
          type: "select",
          items: [
            {
              key: "中标麒麟高级服务器操作系统V7.0",
              name: "中标麒麟高级服务器操作系统V7.0",
            },
            {
              key: "银河麒麟高级服务器操作系统V10(SP1)",
              name: "银河麒麟高级服务器操作系统V10(SP1)",
            },
            {
              key: "银河麒麟高级服务器操作系统V10(SP2)",
              name: "银河麒麟高级服务器操作系统V10(SP2)",
            },
          ],
        },
        architecture: {
          name: "system.architecture",
          type: "select",
          items: [
            {
              key: "aarch64",
              name: "aarch64",
            },
            {
              key: "x86_64",
              name: "x86_64",
            },
          ],
        },
        installTime: {
          name: "system.install_time",
          type: "date",
        },
        scanning: {
          name: "system.scan",
          type: "select",
          items: [
            { key: true, name: this.$t("true") },
            { key: false, name: this.$t("false") },
          ],
        },
      },
    };
  },
  activated() {
      this.$refs.table.handleSearch();
  },
  methods: {
    handleMarkBatchDisplay() {
      this.mark_batch_display = false;
    },
    handleTagClose(value) {
      this.search_criteria.configureObj =
        this.search_criteria.configureObj.filter((item) => item != value);
    },
    handleAddConfigure() {
      if (
        this.search_criteria.configure &&
        this.search_criteria.rule &&
        this.search_criteria.compare_value
      ) {
        this.search_criteria.configureObj.push({
          name: this.search_criteria.configure,
          compare: this.search_criteria.rule,
          value: this.search_criteria.compare_value,
        });
        this.search_criteria.configure = "";
        this.search_criteria.rule = "";
        this.search_criteria.compare_value = "";
      } else {
        this.$message({
          type: "error",
          message: this.$t("system.please_input_configure_information"),
        });
      }
    },
    handlePackageSelect(value) {
      this.search_criteria.pack = value;
      getPackageVersion({ name: value }).then((res) => {
        let versions = new Set(res.data.data);
        this.versions = versions;
      });
    },
    handleConfigureSelect(value) {
      this.search_criteria.configure = value;
    },
    handleCveSelect(value) {
      this.search_criteria.cve = value;
    },
    handleClose() {
      this.display = false;
      this.title = "";
      this.type = "";
    },
    async handleMarkBatch() {
      this.display = true;
      this.title = this.$t("system.mark_batch");
      this.type = "mark_batch";
      if (this.$refs.table.select_id == "2") {
        this.ids = await this.getSelectAllIds();
      } else {
        this.ids = this.$refs.table.selectRow.ids;
      }
    },
    handleDelete(type) {
      this.display = true;
      this.type = "delete";
      let arr = [];
      let str = "";
      if (this.$refs.table.select_id == "2") {
        str = this.$refs.table.select_number.toString();
      } else {
        this.$refs.table.selectRow.rows.map(function (row) {
          arr.push(row.ip);
        });
        str = arr.toString();
      }
      if (type == "upgrade") {
        this.title = this.$t("system.upgrade_agent");
        this.delete_content = this.$t("system.upgrade_agent_content").replace(
          "%s",
          str
        );
      } else {
        this.title = this.$t("system.uninstall_agent");
        this.delete_content = this.$t("system.uninstall_agent_content").replace(
          "%s",
          str
        );
      }
    },
    async getSelectAllIds() {
      let data = [];
      const res = await this.getHostList({
        ...this.$route.query,
        ...this.search_criteria,
        paged: false,
      });
      res.data.data.results.map((item) => {
        if (!this.$refs.table.selectRow.excludeIds.includes(item.id)) {
            data.push(item.id);
        }
      });
      return data;
    },
    async handleDeleteOk() {
      let ids = [];
      let res = null;
      if (this.$refs.table.select_id == "2") {
        ids = await this.getSelectAllIds();
      } else {
        ids = this.$refs.table.selectRow.ids;
      }
      if (this.title == this.$t("system.uninstall_agent")) {
        res = await uninstallAgent(ids);
      } else {
        res = await upgradeAgent(ids);
      }
      if (res.data.code == "0") {
        this.$message({
          type: "success",
          message: res.data.message,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.message,
        });
      }
      this.display = false;
      this.title = "";
      this.type = "";
      this.$refs.table.handleSearch();
    },
    async handleDownloadHost() {
      let ids = [];
      if (this.$refs.table.select_id == "2") {
        ids = await this.getSelectAllIds();
      } else {
        ids = this.$refs.table.selectRow.ids;
      }
      let params = {
        type: this.search_criteria.panel,
        compare: this.search_criteria.rule,
      };
      if (this.search_criteria.panel === 1) {
        params.name = this.search_criteria.pack;
        params.version = this.search_criteria.version;
      } else if (this.search_criteria.panel === 2) {
        params.name = this.search_criteria.pack;
      } else if (this.search_criteria.panel === 3) {
        params.configs = [...this.search_criteria.configureObj];
        params.configs.push({
            name: this.search_criteria.configure,
            compare: this.search_criteria.rule,
            value: this.search_criteria.compare_value
        })
      } else if (this.search_criteria.panel === 4) {
        params.cve = this.search_criteria.cve;
      } else if (this.search_criteria.panel === 5) {
        params.version = this.search_criteria.agentVersion;
      }
      downloadHosts({
        ids,
        ...params,
      }).then((res) => {
        if (res.data.code) {
          this.$message({
            type: "error",
            message: res.data.message,
          });
        } else {
          download(res, "hosts");
        }
      });
    },
    handleSearch() {
      this.$refs.table.handleSearch();
    },
    handleRegister() {
      this.display = true;
      this.title = this.$t("system.register");
      this.type = "register";
    },
    async handleScanNow() {
      let ids = [];
      if (this.$refs.table.select_id == "2") {
        ids = await this.getSelectAllIds();
      } else {
        ids = this.$refs.table.selectRow.ids;
      }
      scanNow({ hostIds: ids }).then((res) => {
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.message,
          });
        }
        this.$router.push({
            name: "log_detail",
            params: { id: res.data.data.id },
          });
      });
    },
    handleCompare() {
      let source = this.$refs.table.selectRow.rows[0].ip;
      let target = this.$refs.table.selectRow.rows[1].ip;
      this.$router.push({
        name: "system_compare",
        query: {
          source,
          target,
        },
      });
    },
    handleReset() {
      this.search_criteria.configure = "";
      this.search_criteria.pack = "";
      this.search_criteria.version = "";
      this.search_criteria.rule = "";
      this.search_criteria.compare_value = "";
      this.search_criteria.cve = [];
      this.search_criteria.agentVersion = "";
      this.versions = [];
      this.search_criteria.configureObj = [];
      this.$refs.table.handleSearch();
    },
    downloadTemplate() {
      downloadTemplate("password_registration_template").then((res) => {
        download(res, "password_registration_template");
      });
    },
  },
  mounted() {
    getAgentVersionList().then((res) => {
      let agentVersions = [];
      let data = new Set(res.data.data);
      Array.from(data).forEach((item) => {
        agentVersions.push({
          id: item.replace("(最新版本)", ""),
          name: item,
        });
      });
      this.agentVersions = agentVersions;
    });
  },
  computed: {
    getHostList() {
      if (this.search_criteria.panel == 1) {
        return getPackageHosts;
      } else if (this.search_criteria.panel == 2) {
        return getPackageChangeHosts;
      } else if (this.search_criteria.panel == 3) {
        return getConfigureHost;
      } else if (this.search_criteria.panel == 4) {
        return getcveHosts;
      } else if (this.search_criteria.panel == 5) {
        return getAgentVersionHost;
      }
    },
  },
  watch: {
    "search_criteria.panel"(val) {
      switch (val) {
        case 1:
        case 2:
          getPackageNames().then((res) => {
            let packages = new Set(res.data.data);
            this.packages = Array.from(packages);
          });
          break;
        case 3:
          getConfigureNames().then((res) => {
            let configure = new Set(res.data.data);
            this.configures = Array.from(configure);
          });
          break;
        case 4:
          getCveNumberList().then((res) => {
            let cves = new Set(res.data.data);
            this.cves = Array.from(cves);
          });
          break;
        case 5:
          getAgentVersionList().then((res) => {
            let agentVersions = [];
            let data = new Set(res.data.data);
            Array.from(data).forEach((item) => {
              agentVersions.push({
                id: item.replace("(最新版本)", ""),
                name: item,
              });
            });
            this.agentVersions = agentVersions;
          });
          break;
      }
      this.search_criteria.configure = "";
      this.search_criteria.pack = "";
      this.search_criteria.version = "";
      this.search_criteria.rule = "";
      this.search_criteria.compare_value = "";
      this.search_criteria.cve = [];
      this.search_criteria.agentVersion = "";
      this.search_criteria.configureObj = [];
      this.versions = [];
      this.$nextTick(() => {
        this.$refs.table.handleSearch();
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.size {
  width: 134px;
}
.label {
  font-weight: 600;
  margin-right: 10px;
}
.success {
  color: #67c23a;
  font-size: 16px;
}
.error {
  color: red;
  font-size: 16px;
}
.kylin-add-button {
  margin-right: 20px;
}
.system-configure-search {
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
}
</style>